<template>
  <div>
    <!--<header-part />-->
    <div class="pay">
      <div class="addresses">
        <el-card shadow="never">
          <div slot="header">确认收货地址</div>
          <div>
            <!--<el-table-->
            <!--    :data="addresses"-->
            <!--    height="250"-->
            <!--    :border="false"-->
            <!--    style="width: 100%">-->
            <!--  <el-table-column width="100">-->
            <!--    <template slot-scope="scope">-->
            <!--      <el-radio v-model="addressId" :label="scope.row.id">&nbsp;</el-radio>-->
            <!--    </template>-->
            <!--  </el-table-column>-->
            <!--  <el-table-column-->
            <!--      prop="consignee"-->
            <!--      label="收件人"-->
            <!--      width="180">-->
            <!--  </el-table-column>-->
            <!--  <el-table-column-->
            <!--      prop="mobile"-->
            <!--      label="手机号"-->
            <!--      width="180">-->
            <!--  </el-table-column>-->
            <!--  <el-table-column-->
            <!--      prop="address"-->
            <!--      label="地址">-->
            <!--  </el-table-column>-->
            <!--</el-table>-->
            <el-radio-group v-model="addressId">
              <div
                class="selectItem"
                v-for="(item, index) in addresses"
                :key="index"
              >
                <el-radio :label="item.id" @change="radioIndex = index">
                  <span> 收货人：{{ item.consignee }} </span>
                  <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                  <span> 电话：{{ item.mobile }} </span>
                  <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                  <span> 详细地址： {{ item.address }}</span>
                </el-radio>
              </div>
            </el-radio-group>
          </div>
        </el-card>
      </div>
      <div class="goods">
        <el-card shadow="never">
          <div slot="header">确认订单信息</div>
          <div>
            <div class="goodsItem" v-for="(item, index) in data" :key="index">
              <el-card shadow="hover">
                <div style="position: relative; top: 0; left: 0">
                  <div class="main">
                    <div class="name">
                      <div class="img">
                        <img
                          :src="item.productImgUrl"
                          alt="商品主图"
                          width="120px"
                          height="120px"
                        />
                      </div>
                      <div class="title">{{ item.sellingPoint }}</div>
                    </div>
                    <div class="value">
                      <div>单价</div>
                      <div>
                        <br/><br/>
                        <span>¥</span>
                        {{ item.productPrice }}
                      </div>
                    </div>
                    <div class="num">
                      <div>数量</div>
                      <div>
                        <br/><br/>
                        {{ item.productCount }}
                      </div>
                    </div>
                    <div class="calc">
                      <div>小计</div>
                      <div>
                        <br/><br/>
                        <span>¥</span>
                        {{ item.total }}
                      </div>
                    </div>
                  </div>
                  <!--<div class="transport">-->
                  <!--  <div>运输方式: 普通快递（运费免邮）</div>-->
                  <!--  <div>运费险：卖家赠送，退换货可赔</div>-->
                  <!--</div>-->
                </div>
              </el-card>
            </div>
          </div>
          <el-divider />
          <div class="bottom">
            收银台 | 结账
            <div class="core">
              <!-- 支付面板 -->
              <el-card shadow="never">
                <div>
                  <span>总计：</span>
                  <span>¥</span>
                  <span>
                    {{ getTotal() | rounding }}
                  </span>
                </div>
                <div>
                  <span>寄送至：</span>
                  <span>
                    {{ addresses[radioIndex]['address'] }}
                  </span>
                </div>
                <div>
                  <span>收件人：</span>
                  <span>
                    {{ addresses[radioIndex]['consignee'] }}
                  </span>
                  <span>
                    {{ addresses[radioIndex]['mobile'] }}
                  </span>
                </div>
              </el-card>
              <!-- 支付面板 -->
              <div class="submitBtn">
                <el-button type="primary" @click="submitPay()">
                  提交订单
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <el-dialog
        title="付款(支付宝付款)"
        :visible.sync="dialogVisible"
        width="40%"
        :center="true"
      >
        <span>
          <div class="qrcode" ref="qrCodeUrl" style="margin-left: 180px"></div>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelPay">取消支付</el-button>
          <el-button type="primary" @click="getPayStatus">支付完成</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getUser } from '../../utils/baseinfo';
import { findAddress } from '../../api/user/address';
import { addOrder, deleteOrder } from '../../api/user/order';
import {
  addPayInfo,
  findPayStatus,
  delPayInfo,
} from '../../api/user/payInfo';
import { deleteCart } from '../../api/user/cart';
import QRCode from 'qrcodejs2';

export default {
  name: 'Pay',
  des: '用户支付页面',
  data() {
    return {
      time: 5,
      radioIndex: 0,
      data: this.$route.params.data,
      addresses: [
        {
          consignee: '',
          address: '',
        },
      ],
      addressId: 0,
      cartId: this.$route.query.cartId,
      dialogVisible: false,
      QRCodeMsg: '',
      orderId: '',
      payInfoId: '',
      outTradeNo: '',
      createFlag: true,
    };
  },
  created() {
    this.getAddress();
  },
  filters: {
    rounding(value) {
      return value.toFixed(2);
    },
  },
  methods: {
    getAddress() {
      const userId = getUser() != null ? getUser().id : '';

      findAddress(userId, 1, 100)
        .then((response) => {
          this.addresses = response.data.addresses;
          this.addressId = this.addresses[0].id;
        })
        .catch((error) => {
          console.log(error);
        });
    },

    getMainImg(item) {
      // let str = item['轮播图'];
      // let arr = str.split('/\r\n');
      // return arr[0];
    },
    getTotal() {
      let total = 0;
      this.data.forEach((item) => {
        total += item.productPrice * item.productCount;
      });
      return total;
    },

    getCount() {
      let total = 0;
      this.data.forEach((item) => {
        total += item.productCount;
      });
      return total;
    },


    submitPay() {
      let str = `总计：${this.$options.filters['rounding'](
        this.getTotal()
      )} , 是否继续支付？`;

      this.$confirm(str, '支付提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'primary',
        center: true,
      })
        .then(async () => {
          const userId = getUser() != null ? getUser().id : '';
          const total = this.getTotal();
          const allCount = this.getCount();

          // 1. 添加订单
          // 请求参数做一下类型转换
          const products = [];
          this.data.forEach((item) => {
            products.push({
              productId: item.productId,
              count: item.productCount,
              price: item.productPrice,
            });
          });
          let response = await addOrder(
            userId,
            total,
            allCount,
            this.addressId,
            products
          );
          console.log('订单添加成功');
          this.orderId = response.data.orderId;

          // 2. 做支付
          response = await addPayInfo(this.orderId);
          this.outTradeNo = response.data.data.out_trade_no;
          this.payInfoId = response.data.payInfoId;
          this.dialogVisible = true;
          this.creatQrCode(response.data.data.qrCode);
          console.log('支付信息创建成功');

        })
        .catch((error) => {
          console.log(error)
          this.$message({
            type: 'info',
            message: '已取消支付',
          });
        });
    },

    async getPayStatus() {
      // 3.查询订单状态
      let response = await findPayStatus(this.outTradeNo);
      this.dialogVisible = false;
      this.createFlag = true;
      this.outTradeNo = ''

      if(response.data.message == '支付成功') {
        console.log("支付成功")

        // 4. 删除购物车信息
        const userId = getUser() != null ? getUser().id : '';
        this.data.forEach(item => {
          if (this.cartId == '') {
            console.log("error: 没有购物车ID参数信息")
            return;
          }
          deleteCart(userId, this.cartId, item.productId)
              .then(response => {
                console.log("购物车信息删除成功")
              })
              .catch(error => {
                console.log("error: " + error);
                return;
              })
        })

        this.$message.success("支付成功");
        this.$router.push({path: '/order'})
      } else {
        this.$message.success("支付失败");
      }
    },

    cancelPay() {
      // 取消支付
      this.dialogVisible = false;
      delPayInfo(this.payInfoId).then(response => {
        console.log(response.data.msg);
      }).catch(error => {
        console.log(error);
      })

      deleteOrder(this.orderId).then(response => {
        console.log('订单删除成功')
      }).catch(error => {
        console.log(error)
      })

    },

    creatQrCode(url) {
      if(this.createFlag) {
        this.createFlag = false;
        this.$nextTick(() => {
          console.log(url);
          let qrcode = new QRCode(this.$refs.qrCodeUrl, {
            text: url,
            width: 200,
            height: 200,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H,
          });
        });
      }
    },
  },
};

</script>

<style scoped lang="less">

.el-dialog__title {
  color: red !important;
}
.pay {
  width: 1200px;
  margin: 0 auto;
  padding: 10px 20px;
}

.selectItem {
  margin: 10px 0;
}

.goods {
  margin-top: 30px;
}

.pay .goods .name {
  display: flex;
}

.pay .goods .title {
  width: 200px;
  height: 70%;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
}

.pay .goods .main {
  display: flex;
  justify-content: space-between;
  text-align: center;
}

.pay .goods .transport {
  position: absolute;
  right: 100px;
  bottom: 4px;
}

.pay .goods .transport {
  color: #666;
}

.pay .goods .transport > div {
  padding: 2px 0;
}

.goodsItem {
  margin-bottom: 20px;
}

.bottom {
  display: flex;
  justify-content: space-between;
}

.bottom .core {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-end;
}

.bottom .core .submitBtn {
  position: relative;
  top: 4px;
  right: 8px;
}
</style>
